// import AsyncStorage from '@react-native-community/async-storage';
function requestPromise(payload = {}) {
    var method = payload.method || 'POST'
    if (method === 'POST') {
        return Post(payload);
    }
    return Get(payload);
}

function requestPromiseJson(payload = {}) {
    var method = payload.method || 'POST'
    if (method === 'POST') {
        return PostJson(payload);
    }
    return Get(payload);
}

function Post(payload) {
    // console.log('payload==>>',payload)
    return fetch(payload.uri, {
        method: "POST",
        mode: "cors",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Connection": "keep-alive"
        },
        body: JSON.stringify(payload.body|| {})
    }).then(response => {
        if (response.ok) {
            return response.json();
        } 
        return response;
    }).then(responseJson => {
         return responseJson;
    }).catch(error => {
        throw error;
    })
}

function PostJson(payload) {
    // console.log('payload==>>',payload)
    return fetch(payload.uri, {
        method: "POST",
        mode: "cors",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json",
            "Connection": "close"
        },
        body:payload.body
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
        return response;
    }).then(responseJson => {
         return responseJson;
    }).catch(error => {
        throw error;
    })
}

function Get(payload) {
    return fetch(payload.uri, {
        method: "GET",
        headers: {
            "Accept": "application/json",
            "Content-Type": "application/json"
        },
    }).then(response => {
        if (response.ok) {
            return response.json();
        }
        return response;
    }).then(responseJson => {
         return responseJson;
    }).catch(error => {
        throw error;
    })
}

function getParams(payload) {
    var uri = ''
    Object.keys(payload).forEach(function (key) {
        uri = uri + key + '=' + payload[key] + '&';
    })
    if(uri.length > 0) {
        uri = uri.substring(0, uri.length - 1);
    }
    return uri;
}

module.exports = {
    requestPromise: requestPromise,
    getParams: getParams,
    requestPromiseJson:requestPromiseJson
}